/**
 * eg : getQueryVariable('id')
 * @param variable
 */
export function getQueryVariable(variable: string) {
  const query = window.location.search.substring(1);
  const vars = query.split('&');
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=');
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
}

/**
 * 千分位加逗号
 * @param val
 */
export function priceFormat(val: number) {
  if (val) {
    return val.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
  } else {
    return '0.00';
  }
}

/**
 * @description 获取代码名称已拼接字符
 * @param code 代码
 * @param name 名称
 * @param strNull 都为空时展示字符
 */
export function getStrByCodeName(code?: string, name?: string, strNull?: string): string {
  if (!code && !name && strNull) {
    return strNull;
  }
  if (code || name) {
    return `${code || ''} [ ${name || ''} ]`;
  }
  return '';
}

/**
 * @description 将各种错误信息转为可展示内容（用于message.error(xx)）
 * @param err 错误信息
 */
export const getErrorMsg = (err: any): string => {
  // 判断是否位表单错误，如果是，则直接提示
  if (err && err.errorFields && err.values) {
    return '请完整填写内容';
  }
  // 后台接口报错
  if (typeof err === 'object' && typeof err.code === 'number') {
    let msg: string = err.message;
    msg = msg.replaceAll('程序发生业务异常:', '');
    msg = msg.replaceAll('更多信息明细:', '');
    if (Array.isArray(err.data) && err.data.lenght) {
      msg += err.data.map((el: any) => el.errorMessage).join('\n');
    }
    return msg;
  }
  if (typeof err === 'string') {
    return err;
  }
  if (err instanceof Error) {
    return err.message;
  }
  return `${err}`;
};
/**
 * @param seconds 秒
 * @param setCountDownSecond
 * @param setVerificationCode 切换获取验证码
 */
export const handleCountDown = (
  seconds: number,
  setCountDownSecond: (arg0: number) => void,
  setVerificationCode: (arg0: boolean) => void,
) => {
  let second = seconds;
  const countDown = () => {
    if (second > 0) {
      second--;
      setCountDownSecond(second);
    }
    if (second === 0) {
      if (seconds === 3) {
        second = 0;
      } else {
        second = 60;
      }
      setCountDownSecond(second);
      setVerificationCode(false);
      return;
    }
    setTimeout(countDown, 1000);
  };
  setTimeout(countDown, 1000);
};

export function phoneNumReg() {
  return /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/;
}
